import configparser
import logging
import os
import sys

from .FwConfigUtils import case_path, listdir
from ..exception.TestException import TestException
from ..exception.errorcode import ErrorCode
from ..utils.robotargumentparser import RobotArgumentParser

logger = logging.getLogger("PageConfig")


class PageConfig:
    def __init__(self):
        config_name = "page.ini"
        if len(sys.argv) > 1:  # 用于判空，不执行robot时，sys.argv为1
            rap = RobotArgumentParser()
            page_name = rap.getZCMVariableValue('zpage')
            if page_name:
                new_config_name = "page-{}.ini".format(page_name)
                if new_config_name in listdir:
                    config_name = new_config_name
                else:
                    logger.error(f"{new_config_name} not find in case path, use default page.ini file")

        self.config_path = os.path.join(case_path, config_name)

        if config_name not in listdir:
            logger.error(f"{config_name} not find in case path")
            self.config = None
        else:
            self.config = configparser.ConfigParser()
            self.config.read(self.config_path, encoding='utf-8')

    def read(self, name):
        splits = name.split('-')
        if len(splits) < 2:
            section = "DEFAULT"
            option = name
        else:
            section = splits[0]
            option = '-'.join(splits[1:])

        return self.read_config(section, option)

    def read_config(self, section, option):
        if not self.config:
            raise TestException.by_error_code(ErrorCode.PARAM_ERROR, message=f"{self.config_path} page config not find")

        try:
            res = self.config.get(section, option)
        except configparser.NoSectionError:
            raise TestException.by_error_code(ErrorCode.PARAM_ERROR,
                                              message=f"page name {section} not find in {self.config_path}")
        except configparser.NoOptionError:
            raise TestException.by_error_code(ErrorCode.PARAM_ERROR,
                                              message=f"element name {option} not find in {section} page of file {self.config_path}")
        else:
            return res


page_parser = PageConfig()
